/*
 * Copyright (c) $year.
 * 网址：http://goour.cn
 * 作者：侯坤林
 * 邮箱：lscode@qq.com
 * 侯坤林 版权所有
 *
 */

package cn.goour.web.base.tools

import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.MessageSource
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.i18n.LocaleContextHolder
import org.springframework.web.servlet.LocaleResolver
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor
import org.springframework.web.servlet.i18n.SessionLocaleResolver
import java.util.*
import javax.annotation.PostConstruct

@Configuration
open class I18nConfig : WebMvcConfigurerAdapter() {
    @Bean
    open fun localeResolver(): LocaleResolver {
        val slr = SessionLocaleResolver()
        slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE)
        return slr
    }

    @Bean
    open fun localeChangeInterceptor(): LocaleChangeInterceptor {
        val lci = LocaleChangeInterceptor()
        lci.paramName = "lang"
        return lci
    }

    override fun addInterceptors(registry: InterceptorRegistry?) {
        registry!!.addInterceptor(localeChangeInterceptor())
    }
}


@Configuration
open class MessageManager {

    @Autowired(required = true)
    fun setMessageSource(messageSource: MessageSource) {
        Companion.messageSource = messageSource
    }

    @PostConstruct
    fun run() {
        logger.info("PostConstruct ${this.javaClass.simpleName}...")
    }

    companion object {

        lateinit var messageSource: MessageSource

        private val logger = LoggerFactory.getLogger(MessageManager::class.java)

        fun getMsg(key: String): String {
            val locale = LocaleContextHolder.getLocale()
            return messageSource.getMessage(key, null, locale)
        }

        fun getMsg(key: String, vararg arg: String): String {
            val locale = LocaleContextHolder.getLocale()
            val args = arrayOfNulls<Any>(arg.size)
            for (i in arg.indices) {
                args[i] = arg[i]
            }
            return messageSource.getMessage(key, args, locale)
        }
    }
}